package com.joint.web.action.com;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.fz.us.dict.service.DictService;
import com.google.common.collect.Sets;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.*;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.service.DepartmentService;
import com.joint.base.service.PostService;
import com.joint.base.service.ReadersService;
import com.joint.base.service.RemindService;
import com.joint.base.util.DataUtil;
import com.joint.base.util.StringUtils;
import com.joint.core.entity.*;
import com.joint.core.service.ApplyService;
import com.joint.core.service.EmployeesService;
import com.joint.core.service.PersonnelResumeService;
import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONObject;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.task.Task;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by root on 16/12/16.
 */
@ParentPackage("com")
public class AjaxApplyAction extends BaseFlowAction {

    @Resource
    private EmployeesService employeesService;
    @Resource
    private ApplyService applyService;
    @Resource
    private DictService dictService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private PostService postService;
    @Resource
    private RemindService remindService;
    @Resource
    private ReadersService readersService;
    @Resource
    private PersonnelResumeService personnelResumeService;

    private Employees employees;
    private Apply apply;
    private String name;
    private String postId;
    private String depId;
    private String startDate;
    private String trialStart;
    private String trialEnd;
    private String endDate;
    private Users loginUser;
    private String nature;
    private String sex;
    private int ifCentralStaff;
    private String ifPersonnel;
    private Users creater;
    private String createDate;
    private Post post;
    private Department department;
    private String gender;
    private String depName;
    private String postName;

    /**
     * 下一步审批人的Name的集合，用逗号分隔
     */
    private String nextStepApproversName;

    /**
     * 下一步审批人的id的集合，用逗号分隔
     */
    private String nextStepApproversId;

    /**
     * 视图类型
     */
    private String viewtype;

    /**
     * 项目视图
     * @return
     */
    public String execute(){
        return "apply";
    }

    /**
     *
     * @return
     */
    public String list(){
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();

        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);
        //所有单子
        params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
        pager=applyService.findByPagerAndLimit(true, "apply", pager, params);

        List<Apply> eList;
        if (pager.getTotalCount() > 0){
            eList = (List<Apply>) pager.getList();
        }else{
            eList = new ArrayList<>();
        }
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(Apply e:eList){
            rMap = new HashMap<String,Object>();
            rMap.put("id",e.getId());
            rMap.put("name",e.getName());
            rMap.put("state",e.getProcessState().value());
            rMap.put("post",e.getPost()==null?"":e.getPost().getName());
            rMap.put("department",e.getDepartment()==null?"":e.getDepartment().getName());
            rMap.put("trialStart",DataUtil.DateToString(e.getTrialStart(),"yyyy-MM-dd"));
            rMap.put("trialEnd",DataUtil.DateToString(e.getTrialEnd(),"yyyy-MM-dd"));
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }
        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);

        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records",recordsNum);

        return  ajaxJson(JSONObject.fromObject(data).toString());
    }


    public String read(){

        loginUser=usersService.getLoginInfo();
        if(StringUtils.isNotEmpty(keyId)){
            apply = applyService.get(keyId);
            numStatus = workflowService.getNumStatus(keyId, loginUser);

        }else {

        }
        return "read";

    }

    public String input(){
        loginUser = usersService.getLoginInfo();
        if(StringUtils.isNotEmpty(keyId)){
            apply = applyService.get(keyId);
            createDate= DataUtil.DateToString(apply.getCreateDate(),"yyyy-MM-dd");
            creater=apply.getCreater();
            post=apply.getPost();
            department= apply.getDepartment();
            employees = apply.getEmployees();

        }else {
            employees = employeesService.get(parentId);
            post=employees.getEmpPost();
            department=employees.getDep();
            creater=loginUser;
            createDate= DataUtil.DateToString(new Date(),"yyyy-MM-dd");

        }
        return "input";

    }

    public void setData(){

        if(StringUtils.isNotEmpty(keyId)){
            apply = applyService.get(keyId);
            employees=apply.getEmployees();
        }else{
            apply = new Apply();
            apply.setCreater(usersService.getLoginInfo());
        }

        if(StringUtils.isNotEmpty(postId)){
            apply.setPost(postService.get(postId));
        }
        if(StringUtils.isNotEmpty(depId)){
            apply.setDepartment(departmentService.get(depId));
        }
        if(StringUtils.isNotEmpty(startDate)){
            apply.setStartDate(DataUtil.StringToDate(startDate));
        }
        if(StringUtils.isNotEmpty(endDate)){
            apply.setEndDate(DataUtil.StringToDate(endDate));
        }
        if(StringUtils.isNotEmpty(trialStart)){
            apply.setTrialStart(DataUtil.StringToDate(trialStart));
        }
        if(StringUtils.isNotEmpty(trialEnd)){
            apply.setTrialEnd(DataUtil.StringToDate(trialEnd));
        }
        //判断是产业中心人员
        Set<Duty> dutySet = usersService.getLoginInfo().getDutySet();
        for (Duty duty:dutySet){
            if(duty.getDepartment().getParent()!=null){
                LogUtil.info("ceshi"+duty.getDepartment().getParent().getName());
                if(org.apache.commons.lang.StringUtils.equals(duty.getDepartment().getParent().getName(),"产业中心")){
                    apply.setIfCentralStaff(1);
                }
            }

        }
        if(StringUtils.isNotEmpty(parentId)){
            employees=employeesService.get(parentId);

        }
        apply.setEmployees(employees);
        apply.setCreater(usersService.getLoginInfo());
        apply.setName(name);
        apply.setNextStepApproversId(nextStepApproversId);
        apply.setNextStepApproversName(nextStepApproversName);
        apply.setCompany(usersService.getLoginInfo().getCompany());

    }

    /**
     * 判断是否为人事专员
     * @return
     */
    public String checkUser(){

        loginUser = usersService.getLoginInfo();
        employees = employeesService.get(parentId);
        Department department = employees.getDep();
        Set<Power> powerSet = department.getPowerSet();
        Map<String,String> data=new HashMap<String, String>();

        LogUtil.info("powerSet"+powerSet);
        for (Power power:powerSet){
            Post post = power.getPost();
            LogUtil.info("post"+post.getName());
            if(StringUtils.equals(post.getName(),"人事专员")){
                List<Users> persons = dutyService.getPersons(department, post);
                for (Users users:persons){
                    if(users.equals(loginUser)){
                        ifPersonnel="1";
                        data.put("ifPersonnel",ifPersonnel);
                    }else {
                        data.put("ifPersonnel",ifPersonnel);
                    }
                }
            }
        }
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }


    /**
     * 员工转正按钮
     */
    public String update(){
        try {
            if(org.apache.commons.lang.StringUtils.isNotEmpty(keyId)){
                Employees entity =employeesService.get(keyId);
                entity.setNature("0");
                employeesService.update(entity);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "保存成功！", "操作状态");

    }
    /**
     * 保存
     * @return
     */
    public String save(){
        setData();
        try {
            if(StringUtils.isNotEmpty(keyId)){
                applyService.update(apply);
            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("curDutyId", curDutyId);
                various.put("initDuty", curDutyId);
                applyService.save(apply, "apply", various);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }

    /**
     * 提交
     * @return
     */
    public String commit(){

        setData();
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);
        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 1);
        var2.put("curDutyId", curDutyId);

        ArrayList<String> list = new ArrayList<String>();
        for (String uid: nextStepApproversId.split(",")) {
            list.add(uid.trim());
        }
        var2.put("approvers", list);    // 会签人Ids
        var2.put("ifCentralStaff", apply.getIfCentralStaff());

        try {
            if (StringUtils.isNotEmpty(keyId)) {
                applyService.approve(apply, FlowEnum.ProcessState.Running, var2, curDutyId,comment);
            }else{
                keyId=applyService.commit(apply, "apply", var1, var2, curDutyId);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        Set<Users> usersSet= Sets.newHashSet();
        usersSet=applyService.get(keyId).getEmployees().getEmployment().getManage().getChargeUsers();

        //增加归档后读者
        for(Users users:usersSet) {
            Readers readers = new Readers();
            readers.setUsers(users);
            readers.setBussinessKey("apply");
            readers.setKeyId(keyId);
            readers.setType(2);
            readersService.save(readers);
        }
        for(Users users:usersSet){
            Remind remind = new Remind();
            remind.setUsers(users);
            remind.setBussinessKey("apply");
            remind.setKeyId(keyId);
            remind.setContent("员工转正已归档");
            remindService.save(remind);
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    /**
     * 审批1
     * @return
     */
    public String approve1(){

        apply= applyService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();
        if(apply.getIfCentralStaff()==1){
            LogUtil.info("ifCentralStaff"+apply.getIfCentralStaff());
            var1.put("numStatus",3);
        }else{
            var1.put("numStatus", 2);
        }

        var1.put("curDutyId", curDutyId);

        try {
            if (org.apache.commons.lang.StringUtils.isNotEmpty(keyId)) {
                applyService.approve(apply, FlowEnum.ProcessState.Running, var1, curDutyId, comment);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }


    /**
     * 审批2
     * @return
     */
    public String approve2() {
        if(org.apache.commons.lang.StringUtils.isEmpty(keyId))return ajaxHtmlCallback("404", "文档ID未找到！", "操作状态");
        if(org.apache.commons.lang.StringUtils.isEmpty(comment)) comment="";
        apply= applyService.get(keyId);

        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 3);
        //  var2.put("curDutyId", curDutyId);
        PersonnelResume personnelResume=new PersonnelResume();

        try {
            applyService.approve(apply, FlowEnum.ProcessState.Finished, var2, curDutyId,comment);

            if(apply.getEmployees()!=null){
                employees = apply.getEmployees();
                if(StringUtils.isNotEmpty(startDate)){
                    employees.setStartDate(DataUtil.StringToDate(startDate));
                }
                if(StringUtils.isNotEmpty(endDate)){
                    employees.setEndDate(DataUtil.StringToDate(endDate));
                }

                apply.setNature("0");
                employees.setNature("0");
                employeesService.update(employees);

                Users users = employees.getUsers();
                personnelResume.setUsers(users);
                personnelResume.setType("转正申请");
                personnelResume.setCompany(usersService.getLoginInfo().getCompany());
                personnelResumeService.save(personnelResume);

            }


        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    /**
     * 会签
     * @return
     */
    public String approve3() {
        if(org.apache.commons.lang.StringUtils.isEmpty(keyId))return ajaxHtmlCallback("404", "文档ID未找到！", "操作状态");
        if(org.apache.commons.lang.StringUtils.isEmpty(comment)) comment="";

        apply = applyService.get(keyId);

        Map<String, Object> var2 = new HashMap<String, Object>();
        // var2.put("curDutyId", curDutyId);
        try {
            applyService.approve(apply, FlowEnum.ProcessState.Running, var2, curDutyId, comment);

            Task overtask = workflowService.getCurrentTask(keyId);
            LogUtil.info("overtask:"+overtask);
            PersonnelResume personnelResume=new PersonnelResume();
            if(overtask==null){
                Apply entity=applyService.get(keyId);
                entity.setProcessState(FlowEnum.ProcessState.Finished);
                applyService.update(entity);
                if(entity.getEmployees()!=null){
                    employees = entity.getEmployees();
                    if(StringUtils.isNotEmpty(startDate)){
                        employees.setStartDate(DataUtil.StringToDate(startDate));
                    }
                    if(StringUtils.isNotEmpty(endDate)){
                        employees.setEndDate(DataUtil.StringToDate(endDate));
                    }

                    employees.setNature("0");
                    employeesService.update(employees);
                }

                Users users = employees.getUsers();
                personnelResume.setUsers(users);
                personnelResume.setType("转正申请");
                personnelResume.setCompany(usersService.getLoginInfo().getCompany());
                personnelResumeService.save(personnelResume);


            }else {

                if(runtimeService.getVariable(overtask.getExecutionId(),"nrOfCompletedInstances")==null){

                    runtimeService.setVariable(overtask.getExecutionId(), "numStatus", 4);
                }
            }

        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }


    /**
     * 退回
     * @return
     */
    public String reject() {
        if (org.apache.commons.lang.StringUtils.isNotEmpty(keyId)) {
            apply = applyService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("apply");
            String key=activityList.get(0).getId();
            System.out.println("Activity key:"+key);
            System.out.println("comment:"+comment);
            LogUtil.info("numStatus:"+numStatus);
            if(StringUtils.isEmpty(comment)) comment="";
            applyService.reject(apply, key, numStatus, comment, curDutyId);
        }

        return ajaxHtmlCallback("200", "退回成功！", "操作状态");
    }

    /**
     * 否决
     * @return
     */
    public String deny() {
        if (StringUtils.isNotEmpty(keyId)) {
            apply = applyService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("apply");
            String key= activityList.get(activityList.size()-1).getId();
            System.out.println("Activity key:"+key);
            if(StringUtils.isEmpty(comment)){
                comment="";
            }
            applyService.deny(apply, key, comment, curDutyId);
        }
        return ajaxHtmlCallback("200", "否决成功！", "操作状态");
    }


    public Apply getApply() {
        return apply;
    }

    public void setApply(Apply apply) {
        this.apply = apply;
    }

    public Employees getEmployees() {
        return employees;
    }

    public void setEmployees(Employees employees) {
        this.employees = employees;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPostId() {
        return postId;
    }

    public void setPostId(String postId) {
        this.postId = postId;
    }

    public String getDepId() {
        return depId;
    }

    public void setDepId(String depId) {
        this.depId = depId;
    }

    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }

    public String getNextStepApproversName() {
        return nextStepApproversName;
    }

    public void setNextStepApproversName(String nextStepApproversName) {
        this.nextStepApproversName = nextStepApproversName;
    }

    public String getNextStepApproversId() {
        return nextStepApproversId;
    }

    public void setNextStepApproversId(String nextStepApproversId) {
        this.nextStepApproversId = nextStepApproversId;
    }

    public String getViewtype() {
        return viewtype;
    }

    public void setViewtype(String viewtype) {
        this.viewtype = viewtype;
    }

    public String getNature() {
        return nature;
    }

    public void setNature(String nature) {
        this.nature = nature;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getIfCentralStaff() {
        return ifCentralStaff;
    }

    public void setIfCentralStaff(int ifCentralStaff) {
        this.ifCentralStaff = ifCentralStaff;
    }

    public String getIfPersonnel() {
        return ifPersonnel;
    }

    public void setIfPersonnel(String ifPersonnel) {
        this.ifPersonnel = ifPersonnel;
    }

    public String getStartDate() {
        return startDate;
    }

    public void setStartDate(String startDate) {
        this.startDate = startDate;
    }

    public String getTrialStart() {
        return trialStart;
    }

    public void setTrialStart(String trialStart) {
        this.trialStart = trialStart;
    }

    public String getTrialEnd() {
        return trialEnd;
    }

    public void setTrialEnd(String trialEnd) {
        this.trialEnd = trialEnd;
    }

    public String getEndDate() {
        return endDate;
    }

    public void setEndDate(String endDate) {
        this.endDate = endDate;
    }

    public Users getCreater() {
        return creater;
    }

    public void setCreater(Users creater) {
        this.creater = creater;
    }

    public String getCreateDate() {
        return createDate;
    }

    public void setCreateDate(String createDate) {
        this.createDate = createDate;
    }

    public Post getPost() {
        return post;
    }

    public void setPost(Post post) {
        this.post = post;
    }

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getDepName() {
        return depName;
    }

    public void setDepName(String depName) {
        this.depName = depName;
    }

    public String getPostName() {
        return postName;
    }

    public void setPostName(String postName) {
        this.postName = postName;
    }
}
